const User = require('../models/userModel');
const { hashPassword, comparePassword } = require('../utils/passwordUtils');
const { generateToken } = require('../config/jwt');

class AuthService {
  // 注册
  static async register(userData) {
    const hashedPassword = await hashPassword(userData.password);
    userData.password = hashedPassword;
    const result = await User.create(userData);    
    // console.log('result',result)
    return {
      id: result.insertId,
      username: userData.username,
      email: userData.email,
      role: userData.role
    };
  }

  // 登录
  static async login(username, password) {
    const user = await User.findByUsername(username);
    if (!user) {
      throw new Error('用户不存在');  
    }

    const isValidPassword = await comparePassword(password, user.password);
    if (!isValidPassword) {
      throw new Error('密码错误');
    }

    const token = generateToken({ 
      id: user.id, 
      username: user.username,
      role: user.role 
    });

    return { user, token };
  }
}

module.exports = AuthService;